import { ECA } from "../eca/eca";
import { Event, EvtHook } from "../eca/event";

const { ccclass, property } = cc._decorator;

@ccclass
export class ECACCNode extends cc.Component {
    @property(cc.JsonAsset)
    configAsset: cc.JsonAsset = null;
    eca: ECA = new ECA();
    evtHook: EvtHook[] = [];

    protected onLoad(): void {
        let eca = new ECA();
        eca.assignFromJSON(this.configAsset.json);
        console.log("ECA:", eca);
        this.setTrigger(eca);
    }

    setTrigger(data: ECA) {
        this.eca = data;
        this.evtHook = [];
        this.eca.evts.forEach(evt => {
            let hook = evt.hook(this);
            hook.onTrigged = this.triggerWithCondition.bind(this);
        });
    }
    triggerWithCondition(...args: any[]) {
        for (let i = 0; i < this.eca.conditions.length; i++) {
            let cond = this.eca.conditions[i];
            if (!cond.check(this)) {
                return;
            }
        }

        this.runActions(...args);
    }
    runActions(...args: any[]) {
        this.eca.actions.forEach(action => {
            action.run(this, ...args);
        });
    }
}